#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
RUNTIME_DIR="${PROJECT_ROOT}/runtime/python-env"
ARCHIVE="${RUNTIME_DIR}/TestAgent-conda-pack.tar.gz"
UNPACKED="${RUNTIME_DIR}/unpacked"
MARKER="${UNPACKED}/.conda_unpacked"

if [[ ! -f "${ARCHIVE}" ]]; then
  echo "[bootstrap-python-env] Missing archive: ${ARCHIVE}" >&2
  exit 1
fi

if [[ ! -d "${UNPACKED}" || ! -x "${UNPACKED}/bin/python" && ! -x "${UNPACKED}/Scripts/python.exe" ]]; then
  echo "[bootstrap-python-env] Extracting Python runtime..."
  mkdir -p "${UNPACKED}"
  tar -xzf "${ARCHIVE}" -C "${UNPACKED}"
fi

PYTHON_BIN="${UNPACKED}/bin/python"
CONDA_UNPACK="${UNPACKED}/bin/conda-unpack"
if [[ "$OS" == "Windows_NT" || "${PYTHON_BIN}" != *"/bin/python" ]]; then
  PYTHON_BIN="${UNPACKED}/Scripts/python.exe"
  CONDA_UNPACK="${UNPACKED}/Scripts/conda-unpack.exe"
fi

if [[ -x "${CONDA_UNPACK}" && ! -f "${MARKER}" ]]; then
  echo "[bootstrap-python-env] Running conda-unpack..."
  "${CONDA_UNPACK}"
  touch "${MARKER}"
fi

echo "[bootstrap-python-env] Python runtime ready at ${UNPACKED}"
echo "export PYTHONHOME=\"${UNPACKED}\""
if [[ -d "${UNPACKED}/bin" ]]; then
  echo "export PATH=\"${UNPACKED}/bin:\$PATH\""
elif [[ -d "${UNPACKED}/Scripts" ]]; then
  echo "export PATH=\"${UNPACKED}/Scripts:\$PATH\""
fi
